package com.ling.controller;

import com.ling.bean.Msg;
import com.ling.bean.User;
import com.ling.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    private final UserService userService;

    @Autowired
    public LoginController(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String goToLogin(){
        return "login";
    }

    //用户登录
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public Msg login(User user,String code,HttpSession session){
        //判断验证码
        String authcode = (String) session.getAttribute("authcode");
        if (!code.equalsIgnoreCase(authcode)) {
            return Msg.fail().add("error", "验证码输入错误！");
        }
        if(userService.checkUser(user)){
            //可以登录,把用户信息放到session中
            session.setAttribute("user",userService.getUser(user.getTel(),user.getPassword()));
            return Msg.success();
        }else{
            return Msg.fail().add("error","用户名和密码不匹配，请重新输入");
        }
    }

}
